package com.codeoss.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.service.impl.BaseService;

@Component
public class Utils implements ApplicationContextAware{
	private static final String HAS_ORDERBY_CLAUSE="__has_orderby_clause__";
	private  ApplicationContext applicationContext;
	public  String getPropertyName(String columnName) {
		String nameArray[]=columnName.split("_");
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<nameArray.length;i++) {
			String s=nameArray[i];
			if(i>0) {
				sb.append(s.substring(0, 1).toUpperCase());
				sb.append(s.substring(1));
			}else {
				sb.append(s);
			}
		}
		return sb.toString();
	}
	
	public  BaseService getBaseService(Table table) {
		String tableName=table.getTableName();
		String nameArray[]=tableName.split("_");
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<nameArray.length;i++) {
			String s=nameArray[i];
			if(i>0) {
				sb.append(s.substring(0,1).toUpperCase());
				sb.append(s.substring(1));
			}else {
				sb.append(s);
			}
		}
		sb.append("Service");
		return (BaseService)applicationContext.getBean(sb.toString());
	}

	public  Object newModelObject(Table table) {
		String packageName=table.getPackageName();
		String tableName=table.getTableName();
		String tableNameArray[]=tableName.split("_");
		String model="";
		for(int i=0;i<tableNameArray.length;i++) {
			model+=tableNameArray[i].substring(0, 1).toUpperCase()+tableNameArray[i].substring(1);
		}
		String className=packageName+".model."+model;
		try {
			Object modelObject=Class.forName(className).newInstance();
			return modelObject;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext=applicationContext;
	}
	
	public void setHasOrderByClause(YunContext yunContext) {
		yunContext.setAttribute(HAS_ORDERBY_CLAUSE, true);
	}
	
	public boolean getHasOrderByClause(YunContext yunContext) {
		Boolean result=yunContext.getAttribute(HAS_ORDERBY_CLAUSE);
		if(result==null) {
			return false;
		}
		return result.booleanValue();
	}
}
